package org.ljy.forum6.services.impl;

import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.ljy.forum6.dao.ArticleReplyMapper;
import org.ljy.forum6.exception.ApplicationException;
import org.ljy.forum6.model.Article;
import org.ljy.forum6.model.ArticleReply;
import org.ljy.forum6.services.IArticleReplyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private ArticleServiceImpl articleService;

    /**
     * 新增回复
     */
    @Override
    public void create(ArticleReply articleReply) {
        //1.参数校验
        if(articleReply == null || articleReply.getArticleId() == null || articleReply.getArticleId() <= 0
        || articleReply.getContent()==null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.文章校验
        Article article = articleService.selectById(articleReply.getArticleId());
        if(article.getDeleteState()==1 || article.getState()==1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //3.设置默认回复对象
        articleReply.setLikeCount(0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setState((byte) 0);
        //articleReply.setPostUserId(article.getUserId());
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //4.调用dao，插入回复对象
        int row  = articleReplyMapper.insertSelective(articleReply);
        if(row != 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //5.更新文章的回复数
        articleService.addOneReplyCountById(article.getId());

    }

    /**
     * 返回文章下的所有回复
     * @param articleId 文章id
     * @return
     */
    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //1.参数校验
        if(articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.调用dao
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        if(articleReplies == null ) {
            articleReplies = new ArrayList<ArticleReply>();
        }
        return articleReplies;
    }
}
